﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Pixysoft.Framework.Security.Entity;
using System.Text.RegularExpressions;
using System.Web.UI;
using Pixysoft.Framework.Noebe.Orm;
using Pixysoft.Framework.Configurations;
using Pixysoft.Web;

namespace Pixysoft.Framework.Security.Controller
{
    class WebAuthController
    {
        /// <summary>
        /// 查看是否有页面访问权限
        /// </summary>
        /// <param name="principal"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static bool PageAuthorizing(UserInfo principal, IHttpHandler handler)
        {
            Page page = handler as Page;

            if (page == null)
                return true;

            object[] ress = page.GetType().GetCustomAttributes(typeof(AuthenticationPageAttribute), true);

            if (ress == null || ress.Length == 0)
                return true;

            foreach (AuthenticationPageAttribute attribute in ress)
            {
                bool found = false;

                foreach (string res in principal.PageResList)
                {
                    if (Regex.Replace(attribute.ResName, res, "", RegexOptions.IgnoreCase).Trim() == "")
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                    return false;
            }

            return true;
        }

        /// <summary>
        /// 查看是否有页面访问权限
        /// </summary>
        /// <param name="principal"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static bool PageAuthorizing(UserInfo principal, string resName)
        {
            foreach (string res in principal.PageResList)
            {
                if (Regex.Replace(resName, res, "", RegexOptions.IgnoreCase).Trim() == "")
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 取得自动登录的信息
        /// </summary>
        /// <returns></returns>
        public static AutoLoginInfo GetAutoLoginInfo()
        {
            string infostring = Pixysoft.Web.CookieHelper.Instance.ExtractTokenFromCookie(HttpContext.Current.Request, StringHelper.cookieName_autologin);

            if (string.IsNullOrEmpty(infostring))
                return null;

            try
            {
                infostring = Pixysoft.Security.DES.Decrypt(infostring, StringHelper.global_framework_id);

                AutoLoginInfo info = XmlManager.Deserialize<AutoLoginInfo>(infostring);

                if (info != null)
                    return info;

                LoggerHelper.Error("deserialize auto login info fail. remove cookie");

                Pixysoft.Web.CookieHelper.Instance.RemoveCookie(HttpContext.Current, StringHelper.cookieName_autologin);

                return null;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(infostring);

                LoggerHelper.Fatal(ex);

                Pixysoft.Web.CookieHelper.Instance.RemoveCookie(HttpContext.Current, StringHelper.cookieName_autologin);

                return null;
            }
        }

        /// <summary>
        /// 设置自动登录属性
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="autoLogin"></param>
        /// <returns></returns>
        public static AutoLoginInfo SetAutoLoginInfo(string username, string password, bool autoLogin)
        {
            string md5password = Pixysoft.Security.MD5.GetMD5(password);
            AutoLoginInfo info = new AutoLoginInfo();
            info.Username = username;
            info.Md5Password = md5password;
            info.IsAutoLogin = autoLogin;
            try
            {
                string infostring = XmlManager.Serialize(info).Serialize();
                infostring = Pixysoft.Security.DES.Encrypt(infostring, StringHelper.global_framework_id);
                CookieHelper.Instance.AddCookie(HttpContext.Current, StringHelper.cookieName_autologin, infostring);
                return info;
            }
            catch (Exception ex)
            {
                LoggerHelper.Fatal(ex);
                return null;
            }
        }

        /// <summary>
        /// 更新自动登录
        /// </summary>
        /// <param name="info"></param>
        public static void UpdateAutoLoginInfo(AutoLoginInfo info)
        {
            try
            {
                string infostring = XmlManager.Serialize(info).Serialize();
                infostring = Pixysoft.Security.DES.Encrypt(infostring, StringHelper.global_framework_id);
                CookieHelper.Instance.AddCookie(HttpContext.Current, StringHelper.cookieName_autologin, infostring);
            }
            catch (Exception ex)
            {
                LoggerHelper.Fatal(ex);
            }
        }

        /// <summary>
        /// 根据token从缓存取得userprofile
        /// </summary>
        /// <returns></returns>
        public static UserInfo GetUserInfo()
        {
            string token = Pixysoft.Web.CookieHelper.Instance.ExtractTokenFromCookie(HttpContext.Current.Request, StringHelper.cookieName_userinfo);

            return GetUserInfo(token);
        }

        /// <summary>
        /// 直接从缓存取得userprofile
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public static UserInfo GetUserInfo(string token)
        {
            if (string.IsNullOrEmpty(token))
                return null;

            UserInfo profile = WebSecurityCacher.Instance.GetUserInfo(token);

            return profile;
        }

        /// <summary>
        /// 新建一个用户档案
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public static UserInfo CreateUserProifile(string loginname, string token)
        {
            UserInfo profile = new UserInfo(loginname, token);

            return profile;
        }

        /// <summary>
        /// 往缓存添加用护
        /// </summary>
        /// <param name="principal"></param>
        public static void AddProfile(UserInfo principal)
        {
            WebSecurityCacher.Instance.RemoveUserInfo(principal.Token);

            WebSecurityCacher.Instance.CacheUserInfo(principal, SettingHelper.timeout);
        }

        /// <summary>
        /// 延长时间
        /// </summary>
        /// <param name="token"></param>
        public static void ExtendProfile(string token)
        {
            WebSecurityCacher.Instance.ExtendUserInfo(token, SettingHelper.timeout);
        }
    }
}
